package com.changxianggu.crawler.cloud.test;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.changxianggu.cloud.crawler.core.WebApplication;
import com.changxianggu.cloud.crawler.core.modules.storage.entity.CxgBook;
import com.changxianggu.cloud.crawler.core.modules.storage.service.ICxgBookService;
import com.changxianggu.cloud.crawler.core.utils.HttpUtil;
import com.changxianggu.cloud.crawler.core.utils.UserAgentUtil;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = {WebApplication.class})// 指定启动类
@Slf4j
public class JiGongJiaoYu {

    @Autowired
    ICxgBookService bookService;

    public static final String COOKIE = "__root_domain_v=.cmpedu.com; _qddaz=QD.xg3bjy.ohvf7f.k6uc5prj; JSESSIONID=D07E1D4183BE25AB4FF94F7BDFAD0CD7; Hm_lvt_f5f40166de163b95a743f8afdac508c3=1587451663; Hm_lpvt_f5f40166de163b95a743f8afdac508c3=1587451836";
    public static final String ORIGIN = "http://book.sciencereading.cn";
    public static final String REFERER = "http://www.cmpedu.com/books/list.htm?p=1&max=12&DISP=3&SORT=";
    public static final String URL_PRE = "http://www.cmpedu.com";


    @Test
    public void initCrawler() throws Exception {
        doCrawler();
    }

    public void doCrawler() throws Exception {
        int pageNum = 45;
        int totalPage = 1123;
        int pageSize = 12;
        for (int i = pageNum; i <= totalPage; i++) {
            String url = "http://www.cmpedu.com/books/list.htm";
            Map<String, Object> parameter = MapUtil.newHashMap(4);
            parameter.put("p", i);
            parameter.put("DISP", 3);
            parameter.put("max", pageSize);
            parameter.put("SORT", "");
            Map<String, Object> headers = MapUtil.newHashMap(5);
            headers.put("Cookie", COOKIE);
            headers.put("User-Agent", UserAgentUtil.random());
            headers.put("Referer", REFERER);
            String result = HttpUtil.doPost(url, headers, parameter);
            while (result.contains("页面没有找到")) {
                //睡眠2秒继续访问
                Thread.sleep(2000);
                result = HttpUtil.doPost(url, headers, parameter);
            }
            if (StrUtil.isNotBlank(result)) {
                Document htmlDoc = Jsoup.parse(result);
                Elements bookContentList = htmlDoc.select(".ts_solgcontlist");
                if (bookContentList != null && bookContentList.size() > 0) {
                    List<CxgBook> listBook = new ArrayList<>();
                    for (Element element : bookContentList) {
                        CxgBook bookEntity = new CxgBook();
                        CxgBook tempEntity = new CxgBook();
                        Element imgElement = element.select(".ts_solg_img").first();
                        if (imgElement != null) {
                            String srcStr = imgElement.attr("src");
                            String cover = srcStr;
                            bookEntity.setCover(cover);
                        }
                        Element titleElement = element.select(".ts_solgcont_title a").first();
                        if (titleElement != null) {
                            String text = titleElement.text();
                            bookEntity.setBookName(text);
                            String href = titleElement.attr("href");
                            String pkId = getNumbers(href);
//                            bookEntity.setDigitalUri(href);
                            bookEntity.setPkId(pkId);
                        }
                        Element authorElement = element.select(".ts_solgcont_cont p").first();
                        if (authorElement != null) {
                            String author = authorElement.text();
                            bookEntity.setAuthor(author);
                        }
                        Element isbnElement = element.select(".ts_solgcont_cont p span").first();
                        if (isbnElement != null) {
                            String isbn = isbnElement.text().replace("ISBN：", "").replace("-", "");
                            bookEntity.setBookIsbn(isbn);
                        }

                        Element pubDateElement = element.select(".ts_solgcont_bot .fr").first();
                        if (pubDateElement != null) {
                            String pubDateStr = pubDateElement.text().replace("出版日期： ", "");
                            if (StrUtil.isNotBlank(pubDateStr)) {
                                pubDateStr = pubDateStr + " 00:00:00";
                                DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                                try {
                                    LocalDateTime localDateTime = LocalDateTime.parse(pubDateStr, dtf);
                                    bookEntity.setPubDate(localDateTime);
                                } catch (Exception e) {

                                }
                            }
                        }
                        bookEntity.setIsSync(0);
                        bookEntity.setCreateTime(LocalDateTime.now());
                        bookEntity.setPressName("机械工业出版社");
                        bookEntity.setStatus(1);
                        //出版社Id不明
                        bookEntity.setPressId(5);

                        Element detailElement = element.select(".ts_solgcontlist a").first();
                        if (detailElement != null) {
                            String href = detailElement.attr("href");
                            String numStr = getNumbers(href);
                            Integer numId = Integer.parseInt(numStr);
                            try {
                                tempEntity = getBookEntity(numId, bookEntity);
                            } catch (Exception e) {
                                tempEntity = bookEntity;
                            }
                        }

                        listBook.add(tempEntity);
                    }
                    bookService.saveBatch(listBook);
                    log.info("第" + i + "页数据保存成功");
                    log.warn("--->" + i);
                }
            }
        }
    }

    public CxgBook getBookEntity(Integer numId, CxgBook bookEntity) throws Exception {
        String url = "http://www.cmpedu.com/books/book/" + numId + ".htm";
        Map<String, Object> headers = MapUtil.newHashMap(5);
        headers.put("Cookie", COOKIE);
        headers.put("User-Agent", UserAgentUtil.random());
        headers.put("Referer", REFERER);
//        String result = HttpUtil.doGet(url, headers, query);
        String result = HttpUtil.doPost(url, headers);
        while (result.contains("页面没有找到")) {
            //睡眠2秒继续访问
            Thread.sleep(2000);
            result = HttpUtil.doPost(url, headers);
        }
        if (StrUtil.isNotBlank(result)) {
            Document htmlDoc = Jsoup.parse(result);
            Element bookContent = htmlDoc.select("body").first();
            if (bookContent != null) {
                Element wordNumElement = bookContent.select(".bd div").eq(6).first();
                if (wordNumElement != null) {
                    String wordNumStr = wordNumElement.text();
                    if (StrUtil.isNotBlank(wordNumStr)) {
                        bookEntity.setWordNum(Integer.parseInt(getNumbers(wordNumStr)));
                    }
                }

                Element authorElement = bookContent.select(".row").eq(3).select(".jg_tsRsjj").first();
                if (authorElement != null) {
                    String authorStr = authorElement.text().replace("作者：", "");
                    if (StrUtil.isNotBlank(authorStr)) {
                        bookEntity.setAuthor(authorStr);
                    }
                }

                Element priceElement = bookContent.select(".bd div").eq(7).first();
                if (priceElement != null) {
                    String priceStr = priceElement.text().replace("定价：", "");
                    if (StrUtil.isNotBlank(priceStr)) {
                        bookEntity.setPrice(new BigDecimal(priceStr));
                    }
                }

                Element digUriElement = bookContent.select("#pdfCp").first();
                if (digUriElement != null) {
                    String digUriStr = digUriElement.attr("href");
                    if (StrUtil.isNotBlank(digUriStr)) {
                        if (digUriStr.contains("http")) {
                            digUriStr = subString(digUriStr, "CHAPTERMODEL=", ".pdf") + ".pdf";
                        }
                        if (digUriStr.contains("pdf") && !digUriStr.contains("upload")) {
                            digUriStr = URL_PRE + digUriStr;
                        }
                        bookEntity.setDigitalUri(digUriStr);
                    }
                }

                Element awardsElement = bookContent.select(".row").eq(3).select(".jg_tsRsjj").eq(2).first();
                if (awardsElement != null) {
                    String awardsStr = awardsElement.text().replace("所属丛书：", "");
                    if (StrUtil.isNotBlank(awardsStr)) {
                        bookEntity.setAwards(awardsStr);
                    }
                }

                //catalog
                Element catalogElement = bookContent.select("#CHAPTERLIST").first();
                if (catalogElement != null) {
                    String catalogStr = catalogElement.text();
                    if (StrUtil.isNotBlank(catalogStr)) {
                        bookEntity.setCatalog(catalogStr);
                    }
                }

                //brief
                Element briefElement = bookContent.select(".jg_tushuRTInfo").first();
                if (briefElement != null) {
                    String briefStr = briefElement.text();
                    if (StrUtil.isNotBlank(briefStr)) {
                        bookEntity.setBrief(briefStr);
                    }
                }

                //印次、版次不明

                //courseware_uri
                Element cuElement = bookContent.select(".xaizaidianji").first();
                if (cuElement != null) {
                    String cuStr = URL_PRE + cuElement.attr("href");
                    if (StrUtil.isNotBlank(cuStr)) {
                        bookEntity.setCoursewareUri(cuStr);
                    }
                }
            }
        }
        return bookEntity;
    }

    /**
     * 判断一个字符串是否都为数字
     *
     * @param strNum
     * @return
     */
    public boolean isDigit(String strNum) {
        Pattern pattern = Pattern.compile("[0-9]{1,}");
        Matcher matcher = pattern.matcher((CharSequence) strNum);
        return matcher.matches();
    }

    /**
     * 截取数字
     *
     * @param content
     * @return
     */
    public String getNumbers(String content) {
        Pattern pattern = Pattern.compile("\\d+");
        Matcher matcher = pattern.matcher(content);
        while (matcher.find()) {
            return matcher.group(0);
        }
        return "";
    }

    /**
     * 截取字符串str中指定字符 strStart、strEnd之间的字符串
     *
     * @return
     */
    public String subString(String str, String strStart, String strEnd) {

        /* 找出指定的2个字符在 该字符串里面的 位置 */
        int strStartIndex = str.indexOf(strStart);
        int strEndIndex = str.indexOf(strEnd);

        /* index 为负数 即表示该字符串中 没有该字符 */
        if (strStartIndex < 0) {
            return "";
        }
        if (strEndIndex < 0) {
            return "";
        }
        /* 开始截取 */
        String result = str.substring(strStartIndex, strEndIndex).substring(strStart.length());
        return result;
    }
}
